package com.mhxy.handler;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mhxy.entity.GameLoginInfo;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class ConfigHandler {

    @Getter
    private static String boxUrl;
    @Getter
    private static String gameUrl;

    @Getter
    private static List<String> boxNames = new ArrayList<>();

    @Getter
    private static List<GameLoginInfo> gameLoginInfos = new ArrayList<>();

    @Getter
    private static GameLoginInfo currentGameLoginInfo;

    public static void loadConfig() {
        String configFilePath;
        if ("prod".equals(getProfiles())) {
            configFilePath = "../config/config.json";
        } else {
            configFilePath = System.getProperty("user.dir") + File.separator + "config/config.json";
        }
        try {
            File configFile = new File(configFilePath);
            log.info("加载配置文件路径：{}", configFile.getAbsolutePath());
            JSONObject jsonObj = JSONUtil.readJSONObject(configFile, StandardCharsets.UTF_8);

            boxUrl = jsonObj.getStr("boxUrl");
            log.info("加载配置信息，boxUrl={}", boxUrl);
            gameUrl = jsonObj.getStr("gameUrl");
            log.info("加载配置信息，gameUrl={}", gameUrl);

            boxNames = JSONUtil.toList(jsonObj.getStr("boxNames"), String.class);
            log.info("加载配置信息，bosNames={}", boxNames);
            gameLoginInfos = JSONUtil.toList(jsonObj.getStr("gameLoginInfos"), GameLoginInfo.class);
            log.info("加载配置信息，gameLoginInfos={}", gameLoginInfos);
            currentGameLoginInfo = gameLoginInfos.get(0);
            log.info("加载配置信息，currentGameLoginInfo={}", currentGameLoginInfo);
        } catch (Exception e) {
            log.error("加载配置信息失败:", e);
            throw new RuntimeException(e);
        }
    }

    public static List<String> getLoginInfoNames() {
        if (gameLoginInfos == null) {
            return new ArrayList<>();
        }
        return gameLoginInfos.stream().map(GameLoginInfo::getInfoName).collect(Collectors.toList());
    }

    public static void switchGameLoginInfo(String infoName) {
        Optional<GameLoginInfo> result = gameLoginInfos.stream().filter(info -> info.getInfoName().equals(infoName)).findFirst();
        result.ifPresent(gameLoginInfo -> currentGameLoginInfo = gameLoginInfo);
        log.info("切换当前登录配置信息: {}", currentGameLoginInfo);
    }

    public static boolean checkCurrentLoginUser(String point) {
        for (String loginUser : currentGameLoginInfo.getLoginUsers()) {
            if (loginUser.contains(point)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 导入Opencv库
     */
    public static void loadOpenCV() {

//        loadLibraryFromClasspath("opencv/opencv_java460.dll");
//        if ("prod".equals(getProfiles())) {
//            loadLibraryFromClasspath("opencv/opencv_java460.dll");
//        } else {
//            URL opencvUrl = ConfigHandler.class.getClassLoader().getResource("opencv");
//            if (opencvUrl == null) {
//                throw new RuntimeException("opencv dir not found");
//            }
//            log.info("Opencv Dir:{}", opencvUrl.getPath());
//            System.loadLibrary(opencvUrl.getPath() + File.separator + "opencv_java460.dll");
//        }

        String path = System.getProperty("user.dir") + File.separator + "otherResources/opencv_java460.dll";
        System.load(path);
        log.info("Opencv加载成功！");
    }

    public static String getProfiles() {
        // 获取当前环境
        String env = System.getProperty("env");
        if (env == null) {
            env = "dev"; // 默认环境
        }
        // prod
        return env;
    }

    public static void loadLibraryFromClasspath(String libraryName) {
        try {
            // 获取库文件的 URL
            URL libraryUrl = ConfigHandler.class.getClassLoader().getResource(libraryName);
            if (libraryUrl == null) {
                throw new RuntimeException("Library not found: " + libraryName);
            }

            // 创建临时文件
            File tempFile = File.createTempFile("lib", getFileExtension(libraryName));
            tempFile.deleteOnExit(); // JVM 退出时删除临时文件

            // 将库文件复制到临时文件
            try (InputStream in = libraryUrl.openStream()) {
                Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            // 加载库
            System.load(tempFile.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException("Failed to load library: " + libraryName, e);
        }
    }

    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex == -1 ? "" : fileName.substring(lastDotIndex);
    }

    public static void main(String[] args) {
        loadConfig();
    }
}
